#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
用户视频管理API
"""

from flask import request, current_app
from flask_restx import Resource, Namespace, fields
from flask_jwt_extended import get_jwt_identity
from app.services.user_video_service import UserVideoService
from app.utils.auth import user_token_required
from app.utils.response import success_response, error_response
from app.utils.validators import validate_required_fields
from . import api

# 创建命名空间
video_ns = Namespace('videos', description='用户视频管理')

# 定义请求模型
video_upload_model = video_ns.model('VideoUpload', {
    'video_url': fields.String(required=True, description='视频URL'),
    'original_name': fields.String(required=True, description='原始文件名'),
    'saved_name': fields.String(description='保存文件名'),
    'file_path': fields.String(description='文件路径'),
    'file_size': fields.Integer(description='文件大小（字节）'),
    'thumbnail_url': fields.String(description='缩略图URL'),
    'duration': fields.Integer(description='视频时长（秒）')
})

video_reorder_model = video_ns.model('VideoReorder', {
    'video_orders': fields.List(
        fields.Raw, 
        required=True, 
        description='视频排序列表',
        example=[
            {'video_id': 1, 'sort_order': 1},
            {'video_id': 2, 'sort_order': 2}
        ]
    )
})

video_audit_model = video_ns.model('VideoAudit', {
    'status': fields.Integer(required=True, description='审核状态：2=通过，3=拒绝'),
    'audit_reason': fields.String(description='审核原因')
})


@video_ns.route('/videos')
class UserVideosAPI(Resource):
    """用户视频列表接口"""
    
    @video_ns.doc('get_user_videos')
    @video_ns.param('include_pending', '是否包含待审核视频', type='bool', default=True)
    @user_token_required
    def get(self, current_user):
        """获取用户视频列表"""
        try:
            include_pending = request.args.get('include_pending', 'true').lower() == 'true'
            
            videos = UserVideoService.get_user_videos(
                current_user.id, 
                include_pending=include_pending
            )
            
            # 获取统计信息
            stats = UserVideoService.get_user_video_stats(current_user.id)
            
            return success_response({
                'videos': videos,
                'stats': stats
            }, '获取成功')
            
        except Exception as e:
            current_app.logger.error(f"获取用户视频异常: {str(e)}")
            return error_response(f"获取失败: {str(e)}", 500)
    
    @video_ns.expect(video_upload_model)
    @video_ns.doc('upload_video')
    @user_token_required
    def post(self, current_user):
        """上传用户视频"""
        try:
            # 验证必填字段
            is_valid, error_msg = validate_required_fields(['video_url', 'original_name'])
            if not is_valid:
                return error_response(error_msg, 400)
            
            data = request.get_json()
            
            # 上传视频
            result = UserVideoService.upload_video(current_user.id, data)
            
            if not result['success']:
                return error_response(result['error'], 400)
            
            return success_response(result['data'], result['message'])
            
        except Exception as e:
            current_app.logger.error(f"上传视频异常: {str(e)}")
            return error_response(f"上传失败: {str(e)}", 500)


@video_ns.route('/videos/<int:video_id>')
class UserVideoDetailAPI(Resource):
    """用户视频详情接口"""
    
    @video_ns.doc('get_video_detail')
    @user_token_required
    def get(self, video_id, current_user):
        """获取视频详情"""
        try:
            video_data = UserVideoService.get_video_detail(video_id, current_user.id)
            
            if not video_data:
                return error_response('视频不存在', 404)
            
            return success_response(video_data, '获取成功')
            
        except Exception as e:
            current_app.logger.error(f"获取视频详情异常: {str(e)}")
            return error_response(f"获取失败: {str(e)}", 500)
    
    @video_ns.doc('delete_video')
    @user_token_required
    def delete(self, video_id, current_user):
        """删除用户视频"""
        try:
            result = UserVideoService.delete_video(current_user.id, video_id)
            
            if not result['success']:
                return error_response(result['error'], 400)
            
            return success_response(message=result['message'])
            
        except Exception as e:
            current_app.logger.error(f"删除视频异常: {str(e)}")
            return error_response(f"删除失败: {str(e)}", 500)


@video_ns.route('/videos/reorder')
class VideoReorderAPI(Resource):
    """视频排序接口"""
    
    @video_ns.expect(video_reorder_model)
    @video_ns.doc('reorder_videos')
    @user_token_required
    def post(self, current_user):
        """重新排序用户视频"""
        try:
            # 验证必填字段
            is_valid, error_msg = validate_required_fields(['video_orders'])
            if not is_valid:
                return error_response(error_msg, 400)
            
            data = request.get_json()
            video_orders = data.get('video_orders', [])
            
            # 验证排序数据格式
            if not isinstance(video_orders, list) or not video_orders:
                return error_response('视频排序数据格式错误', 400)
            
            for item in video_orders:
                if not isinstance(item, dict) or 'video_id' not in item or 'sort_order' not in item:
                    return error_response('排序项格式错误，需要包含video_id和sort_order', 400)
            
            # 执行排序
            result = UserVideoService.reorder_videos(current_user.id, video_orders)
            
            if not result['success']:
                return error_response(result['error'], 400)
            
            return success_response(result['data'], result['message'])
            
        except Exception as e:
            current_app.logger.error(f"视频排序异常: {str(e)}")
            return error_response(f"排序失败: {str(e)}", 500)


@video_ns.route('/videos/stats')
class VideoStatsAPI(Resource):
    """用户视频统计接口"""
    
    @video_ns.doc('get_video_stats')
    @user_token_required
    def get(self, current_user):
        """获取用户视频统计信息"""
        try:
            stats = UserVideoService.get_user_video_stats(current_user.id)
            
            return success_response(stats, '获取统计信息成功')
            
        except Exception as e:
            current_app.logger.error(f"获取视频统计异常: {str(e)}")
            return error_response(f"获取失败: {str(e)}", 500)


@video_ns.route('/admin/videos/pending')
class AdminPendingVideosAPI(Resource):
    """管理员待审核视频接口"""
    
    @video_ns.doc('get_pending_videos')
    @video_ns.param('page', '页码', type='int', default=1)
    @video_ns.param('per_page', '每页数量', type='int', default=20)
    @user_token_required
    def get(self, current_user):
        """获取待审核视频列表（管理员）"""
        try:
            # 这里应该验证管理员权限
            # if not current_user.is_admin:
            #     return error_response('无权限访问', 403)
            
            page = int(request.args.get('page', 1))
            per_page = int(request.args.get('per_page', 20))
            
            if per_page > 100:  # 限制每页最大数量
                per_page = 100
            
            result = UserVideoService.get_pending_videos(page, per_page)
            
            return success_response(result, '获取待审核视频成功')
            
        except Exception as e:
            current_app.logger.error(f"获取待审核视频异常: {str(e)}")
            return error_response(f"获取失败: {str(e)}", 500)


@video_ns.route('/admin/videos/<int:video_id>/audit')
class AdminVideoAuditAPI(Resource):
    """管理员视频审核接口"""
    
    @video_ns.expect(video_audit_model)
    @video_ns.doc('audit_video')
    @user_token_required
    def post(self, video_id, current_user):
        """审核用户视频（管理员）"""
        try:
            # 这里应该验证管理员权限
            # if not current_user.is_admin:
            #     return error_response('无权限访问', 403)
            
            # 验证必填字段
            is_valid, error_msg = validate_required_fields(['status'])
            if not is_valid:
                return error_response(error_msg, 400)
            
            data = request.get_json()
            status = data.get('status')
            audit_reason = data.get('audit_reason', '')
            
            # 验证状态值
            if status not in [2, 3]:  # 2=通过，3=拒绝
                return error_response('无效的审核状态，只能为2(通过)或3(拒绝)', 400)
            
            # 如果拒绝，审核原因必填
            if status == 3 and not audit_reason.strip():
                return error_response('拒绝审核必须填写原因', 400)
            
            # 执行审核
            result = UserVideoService.audit_video(video_id, status, audit_reason)
            
            if not result['success']:
                return error_response(result['error'], 400)
            
            return success_response(result['data'], result['message'])
            
        except Exception as e:
            current_app.logger.error(f"审核视频异常: {str(e)}")
            return error_response(f"审核失败: {str(e)}", 500)


# 将命名空间注册到API实例
api.add_namespace(video_ns) 